package com.example.ui.leftmenu;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.eton.czh.GifView;
import com.example.DBHelper.Dao;
import com.example.downloadmanager.Downloader;
import com.example.huashangapp.BaseView;
import com.example.huashangapp.HSApplication;
import com.example.huashangapp.MyMoveView;
import com.example.huashangapp.R;
import com.example.net.AnalyzingJson;
import com.example.net.NetRequest;
import com.example.service.MainService;
import com.example.ui.MainActivity;
import com.example.ui.learn.CurriculumCenterActivity;
import com.example.ui.learn.DownHandler;
import com.example.ui.learn.DownUtils;
import com.example.ui.learn.ListAdapter;
import com.example.ui.learn.ListeningActivity;
import com.example.ui.learn.ListeningInfo;
import com.example.ui.learn.RecommendActivity;
import com.example.ui.learn.ShareActivity;
import com.example.ui.learn.StartActivity;

import com.example.ui.learn.util.Listen;
import com.example.ui.learn.util.MyClassroom;
import com.example.ui.learn.util.MyListViewAdapter3;

import com.example.util.AsyncLoadImage;
import com.example.util.RefreshableListView;
import com.example.util.RefreshableListView.OnRefreshListener;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Item02View extends BaseView {
	private Context context;
	private MyListViewAdapter3 item_adapter;
	private ArrayList<MyClassroom> i2_mc = new ArrayList<MyClassroom>();
	private Button titleLeftBtn, titleRightBtn; 
	private TextView titleText;
	private MyMoveView moveView;
	private static MainActivity mainActivity;
	private LeftMenuView leftMenuView;
	private String data;
	private String id;
	private Button check, share, download, exit;
	private int fileSize;
	private int downLoadFileSize;
	private ImageView i_v;
	private String filename;
	private String uri;
	private ArrayList<Listen> la_l;
	private ArrayList<Listen> Down_la_l=new ArrayList<Listen>();;
	private LinearLayout i2_ll;
	private String blId;
	MyClassroom mc ;
	private RelativeLayout i2_rl;
	private RefreshableListView mListView;
	private AsyncLoadImage asyncLoadImage;
	String filepath;
	private int lis_id;
	Timer t;
	AlertDialog infoad;
	AlertDialog.Builder bulider;
	private GifView mygifView;
	public Item02View(Context context, MainActivity mainActivity2,LeftMenuView leftMenuView) {
		this.context = context;
		moveView = new MyMoveView(context);
		mainActivity=mainActivity2;
		dao=HSApplication.getDao();
		this.leftMenuView=leftMenuView;
	}
   public void getData(){
		if(HSApplication.i2_mc.size()>0){
			i2_mc=HSApplication.i2_mc;
			item_adapter.setCcInfos(i2_mc);
			item_adapter.notifyDataSetChanged();
		}else{
			 bulider = new AlertDialog.Builder(context);
				bulider.setView(View.inflate(context, R.layout.onloading, null))
						.create();
				infoad = bulider.show();
				new Thread(item2_run).start();  
		}
   }
	public void init() {	
		view = LayoutInflater.from(context).inflate(R.layout.item02, null);
		@SuppressWarnings("unused")
		LayoutInflater layoutinflater= ((LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE));
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			filepath = Environment.getExternalStorageDirectory().toString()
					+ "/huashang/";
		}
		asyncLoadImage = new AsyncLoadImage();
		//check = (Button) view.findViewById(R.id.i2_check);
		share = (Button) view.findViewById(R.id.i2_share);
		i2_rl = (RelativeLayout) view.findViewById(R.id.i2_rl);
		download = (Button) view.findViewById(R.id.i2_download);
		exit = (Button) view.findViewById(R.id.i2_exit);
		i2_ll = (LinearLayout) view.findViewById(R.id.i2_bottom);
		titleLeftBtn = (Button) view.findViewById(R.id.layout_title_left_btn);
		titleRightBtn = (Button) view.findViewById(R.id.layout_title_right_btn);
		titleText = (TextView) view.findViewById(R.id.layout_title_middle_text);
		//i_v=(ImageView)view.findViewById(R.id.i_v);
		mListView = (RefreshableListView) view
				.findViewById(R.id.item01_listview);
		RelativeLayout relation=(RelativeLayout) view.findViewById(R.id.title_main);
		titleText.setText("我的收藏");
		titleLeftBtn.setText("菜单");
		titleRightBtn.setText("正在听");
		Resources r = context.getResources(); 
		int btn_h = (int) r.getDimension(R.dimen.ting_left);
		int btn_left=(int)r.getDimension(R.dimen.text_left);
		titleRightBtn.setPadding(btn_left, 0,  btn_h, 0);
		mygifView = (GifView)view.findViewById(R.id.testView);
		mygifView.setGifImage(R.drawable.ting);
		mygifView.setVisibility(0);
		item_adapter = new MyListViewAdapter3(context, i2_mc,
				new AsyncLoadImage());
		mListView.setAdapter(item_adapter);
		i2_rl.setOnClickListener(i2_ocl);
		//check.setOnClickListener(i2_ocl);
		share.setOnClickListener(i2_ocl);
		download.setOnClickListener(i2_ocl);
		exit.setOnClickListener(i2_ocl);
		titleLeftBtn.setOnClickListener(i2_ocl);
		titleRightBtn.setOnClickListener(i2_ocl);
		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				lis_id=position;
				id = i2_mc.get(position).getId();
				blId = i2_mc.get(position).getBlId();
				final String url=i2_mc.get(position).getPic();
				/*i_v.setTag(url);
				asyncLoadImage.imageLoader.displayImage(url, i_v,asyncLoadImage.options);*/
				switch (i2_ll.getVisibility()) {
				case View.GONE:
					i2_ll.setVisibility(view.VISIBLE);
					break;
				case View.VISIBLE:
					i2_ll.setVisibility(view.GONE);
					break;
				default:
					break;
				}
			}
		});
		mListView.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh(RefreshableListView listView) {
				new NewDataTask().execute();
			}
		});
		//请求数据
		 getData();
	}
	Runnable item2_run = new Runnable() {
		@Override
		public void run() {
			data = NetRequest.Request_Item02();
			JSONObject j;
			try {
				j = new JSONObject(data);
				String result = j.getString("response");
				if (result.equals("true")) {
					i2_mc = AnalyzingJson.getdata_item2(data);
					HSApplication.i2_mc=i2_mc;
					h.sendEmptyMessage(1);
				} else if(result.equals("error")){
					h.sendEmptyMessage(3);
				}
			} catch (Exception e) {
				h.sendEmptyMessage(0);
				e.printStackTrace();
			}
		}
	};
	int i = 0;
	private Notification notif;
	NotificationManager nm;
	Handler h = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				infoad.dismiss();
				Toast.makeText(context, "提取数据异常", Toast.LENGTH_SHORT).show();
				break;
			case 1:
				infoad.dismiss();
				item_adapter.setCcInfos(i2_mc);
				item_adapter.notifyDataSetChanged();
				break;
			case 2:
				String title=i2_mc.get(lis_id).getTitle();
				if (!isWIFI()) {
						return;
					}else{
						checkFile();
						initDown(lis_id);
						Toast.makeText(context, "您下载了("+title+")系列课程", Toast.LENGTH_SHORT).show();
					}
				DownUtils.adapter = new ListAdapter(mainActivity,DownUtils.downUrl);
				DownUtils.adapter.notifyDataSetChanged();
				break;
			case 3:
				infoad.dismiss();
				Toast.makeText(context, "该课程暂无数据", Toast.LENGTH_SHORT).show();
				break;
			case 4:
				Toast.makeText(context, "取消学习成功", Toast.LENGTH_SHORT).show();
				bulider = new AlertDialog.Builder(context);
				bulider.setView(View.inflate(context, R.layout.onloading, null))
							.create();
					infoad = bulider.show();
				new Thread(item2_run).start(); 
				break;
			case 5:
				Toast.makeText(context, "操作失败", Toast.LENGTH_SHORT).show();
				break;
			case 6:
				Toast.makeText(context, "下载完成", Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		}
	};

	private class NewDataTask extends AsyncTask<Void, Void, String> {
		@Override
		protected String doInBackground(Void... params) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
			}
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			bulider = new AlertDialog.Builder(context);
			bulider.setView(View.inflate(context, R.layout.onloading, null))
						.create();
				infoad = bulider.show();
			new Thread(item2_run).start(); 
			mListView.completeRefreshing();
			super.onPostExecute(result);
		}
	}

	Runnable listen_run2 = new Runnable() {
		@Override
		public void run() {
			data = NetRequest.Request_listen(id);
			JSONObject j;
			try {
				j = new JSONObject(data);
				String result = j.getString("response");
				if (result.equals("true")) {
					la_l = AnalyzingJson.getdata_la(data);
					h.sendEmptyMessage(2);
				} else if(result.equals("error")) {
					h.sendEmptyMessage(3);
				}
			} catch (JSONException e) {
				
				e.printStackTrace();
			}
		}
	};  
	Runnable exit_run = new Runnable() {
		@Override
		public void run() {
			String data = null;
			data = NetRequest.Request_deleteCourse(id);
			String result = AnalyzingJson.getcontent_result(data);
			if (result.equals("true")) {
				h.sendEmptyMessage(4);
			} else {
				h.sendEmptyMessage(5);
			}

		}
	};
	
	private OnClickListener i2_ocl = new OnClickListener() {

		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.i2_rl:
				i2_ll.setVisibility(view.GONE);
				break;
		/*	case R.id.i2_check:
				Intent cca_l = new Intent();
				cca_l.putExtra("blId", blId);
				cca_l.setClass(context, RecommendActivity.class);
				context.startActivity(cca_l);
				break;*/
			case R.id.i2_download:

				new Thread(listen_run2).start();
				break;
			case R.id.i2_share:
				Intent i = new Intent();
				i.putExtra("imageUrl",i2_mc.get(lis_id).getPic());
				i.putExtra("title",i2_mc.get(lis_id).getTitle());
				i.putExtra("name", i2_mc.get(lis_id).getName());
				if(Down_la_l.size()>0){
					i.putExtra("musicUrl",Down_la_l.get(0).getUrl());
				}else{
					i.putExtra("musicUrl","");
				}
				i.setClass(context, ShareActivity.class);
				context.startActivity(i);
				break;
			case R.id.i2_exit:
				i2_mc.clear();
				item_adapter.notifyDataSetChanged();
				i2_ll.setVisibility(view.GONE);
				new Thread(exit_run).start();
				break;
			case R.id.layout_title_left_btn:
				myMoveView.showHideLeftMenu();
				break;
			case R.id.layout_title_right_btn:
				if(HSApplication.HSlistInfo.getListen_uri()==null||"".equals(HSApplication.HSlistInfo.getListen_uri())){
					Toast.makeText(context, "目前您还没有收听过任何课程!",Toast.LENGTH_SHORT).show();
					return;
				}
				Intent i1_l = new Intent();
				i1_l.setClass(context, ListeningActivity.class);
				Bundle lisinfo=new Bundle();
				lisinfo.putParcelable(ListeningActivity.LISTEN,HSApplication.HSlistInfo);
				i1_l.putExtras(lisinfo);
				i1_l.putExtra(ListeningActivity.ISLISTENING,true);
				context.startActivity(i1_l);
				break;
			default:
				break;
			}
		}
	};

	private boolean netWork;
	private ArrayList<String> list_mp3 = new ArrayList<String>();

	
	protected void checkFile() {
			for (Listen lis :  la_l) {
				String lisname=lis.getUrl().substring(lis.getUrl().lastIndexOf("/") + 1);
				File f = new File(filepath+lisname);
				if(f.exists())
				    continue;
				else
					Down_la_l.add(lis);
			}
	}
	private void searchFiles(File f) {
		list_mp3.clear();
		File files[] = f.listFiles();
		for (File tempF : files) {
			if(tempF==null){
				continue;
			}
			if (tempF.isDirectory()) {
				searchFiles(tempF);
			} else {
				String path = tempF.getPath();
				String fpath = path.substring(path.lastIndexOf(".") + 1,
						path.length());
				if (fpath.equals("mp3")) {
					String mp3 = path.substring(path.lastIndexOf("/") + 1);
					list_mp3.add(mp3);
				}
			}
		}
	}

	public boolean isWIFI(){
		 netWork=false;
		String  net = MainService.setNetworkType(context);
		if ("".equals(net)) {
			new AlertDialog.Builder(context)
			.setTitle("当前没有可用的网络")
			.setMessage("请开启网络")
			.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog,
								int which) {
							 netWork=false;
						}
					}).show();
		} else if("wifi".equals(net)){
					netWork=true;
		}else{
			new AlertDialog.Builder(context)
					.setTitle("当前不是wifi环境!")
					.setMessage("确认要继续下载吗?")	
					.setNegativeButton(
							"取消",
							new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									 netWork=false;
								}
							})
					.setPositiveButton(
							"确定",
							new android.content.DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									netWork=true;
								}
							}).show();
		}
	return netWork;
	}
	 DownItem di=null;
	 Handler image_H=new Handler(){
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					i_v.setImageDrawable((Drawable)msg.obj);
					break;
				default:
					break;
					}
				}
			};
			ListeningInfo listen;
			private Dao dao;
	public void initDown(int position){
	
		mc = i2_mc.get(position);
		for (int i = 0; i < Down_la_l.size(); i++) {
			di=new DownItem(context);
			di.setTitle(mc.getTitle());
			di.setName(mc.getName());
			di.setSub_title(Down_la_l.get(i).getTitle());
			di.setUrl(Down_la_l.get(i).getUrl());
			di.setPic_Url(mc.getPic());
			di.setTer_Id(blId);
			di.setColum_Id(id);
			di.setTag(1);
			di.setIsCollet(Boolean.parseBoolean(
					i2_mc.get(lis_id).getIntro()));
			listen=new ListeningInfo(Down_la_l.get(i).getUrl(), di.getPic_Url(), di.getTitle(),di.getName(),di.getTer_Id(),di.getTag(),di.getColum_Id(),di.getSub_title(),-1,0,0);
			dao.saveListenDown(listen);
			@SuppressWarnings("rawtypes")
			Downloader downloader = new Downloader(Down_la_l.get(i).getUrl(), filepath,1,this.context,new DownHandler());
			boolean isdowning=false;
			for (String uri : DownUtils.listDownItem.keySet()) {
				if(Down_la_l.get(i).getUrl().equals(uri)){
					isdowning=true;
					break;
				}
			}
			if(isdowning){
				continue;
			}
			DownUtils.listDownItem.put(Down_la_l.get(i).getUrl(), di);
			DownUtils.downUrl.add(Down_la_l.get(i).getUrl());
			DownUtils.downloaders.put(Down_la_l.get(i).getUrl(),downloader);
		}
			for (int i = 0; i <DownUtils.downUrl.size(); i++) {
				String tag=DownUtils.downUrl.get(i);
				if(!DownUtils.listDownItem.get(tag).isDowned&&(DownUtils.downCount-DownUtils.downIngCount)>0){
					DownUtils.listDownItem.get(tag).isDowned=true;
					DownUtils.downloaders.get(tag).init();
					dao.deleteListenDown(tag);
					DownUtils.downIngCount++;
				}
			}
	}
}